package zisu.algorithm.algorithm.LinkedList;

/**
 * @Author: 蔡翔
 * @Date: 2019/12/6 9:44
 * @Version 1.0
 */

/**
 * 删除链表中等于给定值 val 的所有节点。
 *
 * 输入: 1->2->6->3->4->5->6, val = 6
 * 输出: 1->2->3->4->5
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution203 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    public ListNode removeElements(ListNode head, int val) {
        while (head !=null && head.val ==val){
            ListNode delNode = head;
            head = head.next;
            delNode.next = null;
        }
        if(head == null){
            return head;
        }

        ListNode pre = head;
        while (pre.next != null){
            ListNode cur = pre.next;
            if(cur.val == val){
                pre.next = cur.next;
                cur.next = null;
            }else {
                pre = pre.next;
            }
        }
        return head;
    }
}
